import React, { useEffect, useRef, useState } from "react";
import TheButton from "@/components/TheButton";
import TheTable from "@/components/TheTable";
import ThePagination from "@/components/ThePagination";
import TheDialog from "@/components/TheDialog";
import { Button, Form, Input, Space } from "antd";
import { apiGetAdoptLabelPage, apiGetAdoptLabelAdd, apiGetAdoptLabelEdit, apiGetAdoptLabelDel } from '@/request/adopt'

const Editor = ({ type, editorValue, reload, handleCancel, petLabelId }) => {
  const formRef = useRef()
  const [btnLoading, setBtnLoading] = useState(false)
  useEffect(() => {
    if (type === 'editor') {
      formRef.current.setFieldsValue({ petLabelName: editorValue.petLabelName })
    }
  }, [])
  const onFinish = async values => {
    setBtnLoading(true)
    if (type === 'editor') {
      let response = await apiGetAdoptLabelEdit({ ...values, petLabelId })
      if (response.code === 0) {
        handleCancel()
        setBtnLoading(false)
        React.$message({
          type: 'info',
          content: '修改成功'
        })
        reload()
      }
    } else {
      let res = await apiGetAdoptLabelAdd({ ...values })
      if (res.code === 0) {
        handleCancel()
        setBtnLoading(false)
        React.$message({
          type: 'info',
          content: '修改成功'
        })
        reload()
      }
    }
  }
  return <Form ref={formRef} onFinish={onFinish}>
    <Form.Item label="名称" name={'petLabelName'} rules={[{ required: true }]}>
      <Input maxLength={4}/>
    </Form.Item>
    <Form.Item>
      <div style={{ display: "flex", justifyContent: "flex-end" }}>
        <Space>
          <Button onClick={handleCancel}>取消</Button>
          <Button loading={btnLoading} htmlType="submit" type="primary">保存</Button>
        </Space>
      </div>
    </Form.Item>
  </Form>
}

class Tags extends React.Component {
  formRef = React.createRef()
  state = {
    columns: [
      {
        title: "宠物标签",
        dataIndex: "petLabelName",
        key: "petLabelName",
      },
      {
        title: "操作",
        render: (text, render) => {
          return (
            <div>
              <TheButton    haspermi={['adopt:tags:update']}  onClick={() => this.openDialog('editor', render, render.petLabelId)}>修改</TheButton>
              <TheButton haspermi={['adopt:tags:delete']} onClick={() => this.deleteConfirm(render.petLabelId)}>删除</TheButton>
            </div>
          );
        },
      },
    ],
    dataSource: [],
    pageData: {
      pageNo: 1,
      pageSize: 10,
    },
    total: 500,
    visible: false,
    title: "",
  };
  componentDidMount() {
    this.getData()
  }
  getData = async () => {
    const { pageData } = this.state
    let res = await apiGetAdoptLabelPage({ ...pageData })
    if (res.data && res.code === 0) {
      this.setState({
        pageData: {
          pageNo: res.pageNo,
          pageSize: res.pageSize
        },
        total: res.totalCount,
        dataSource: res.data
      })
    }
  }
  pageChange = (pageNo, pageSize) => {
    this.setState({
      pageData: {
        pageNo, pageSize
      }
    }, () => this.getData())
  }
  openDialog = (type, editorValue, petLabelId) => {
    if (type === "editor")
      this.setState({ visible: true, title: "修改宠物标签", petLabelId, editorValue, type: 'editor' });
    if (type === "add")
      this.setState({
        visible: true,
        title: "新增宠物标签",
        petLabelId: '',
        type: 'add'
      });
  };
  handleCancel = () => {
    this.setState({ visible: false, title: "", petLabelId: '' });
  };
  deleteConfirm = (petLabelId) => {
    React.$confirm({
      title: "您确认删除此条宠物标签吗？",
      onOk: async () => {
        let res = await apiGetAdoptLabelDel({ petLabelId })
        if (res.code === 0) {
          React.$message({
            type: 'info',
            content: '删除成功'
          })
          this.getData()
        }
      },
    });
  };
  render() {
    const {
      columns,
      dataSource,
      pageData: { pageNo, pageSize },
      total,
      title,
      visible,
      editorValue,
      petLabelId,
      type
    } = this.state;
    return (
      <div className="p-layout-box">
        <div style={{ display: "flex", justifyContent: "flex-end" }}>
          <TheButton
          haspermi={['adopt:tags:add']}
            type="default"
            size="middle"
            onClick={() => this.openDialog("add")}
          >
            新增标签
          </TheButton>
        </div>
        <div className="p-layout-content-pagination">
          <TheTable columns={columns} dataSource={dataSource} scroll={{ x: 'max-content', y: '63vh' }} />
          <ThePagination
            pageNo={pageNo}
            pageSize={pageSize}
            total={total}
            pageChange={this.pageChange}
          />
        </div>
        <TheDialog
          title={title}
          visible={visible}
          width={400}
          footer={null}
          handleCancel={this.handleCancel}
        >
          <Editor editorValue={editorValue} petLabelId={petLabelId} type={type} reload={this.getData}
            handleCancel={this.handleCancel} setBtnLoading={this.setBtnLoading}
          />
        </TheDialog>
      </div>
    );
  }
}

export default Tags;
